from typing import Optional, Dict, List, Tuple
import pandas as pd
from PySide6.QtCore import QObject, Signal, QTimer
from loguru import logger
from ui.workers import SlowProcessWorker
from ..models.basis_monitor_model import BasisMonitorModel


class BasisMonitorController(QObject):
    
    index_data_loaded = Signal(object)  # pd.DataFrame
    futures_data_loaded = Signal(object)  # pd.DataFrame
    loading_state_changed = Signal(bool)  # is_loading
    chart_data_ready = Signal(str, str)  # chart_type, symbol
    
    def __init__(self):
        super().__init__()
        self.model = BasisMonitorModel()
        self.worker = None
        self.refresh_timer = QTimer()
        self.refresh_timer.timeout.connect(self.refresh_data)
        self._is_shutting_down = False
        
    def start_auto_refresh(self, interval_ms: int = 10000):
        self.refresh_timer.start(interval_ms)
        
    def stop_auto_refresh(self):
        if self.refresh_timer.isActive():
            self.refresh_timer.stop()
            
    def refresh_data(self):
        if self._is_shutting_down:
            return
            
        if self.worker and self.worker.isRunning():
            logger.debug("Data refresh already in progress, skipping...")
            return
            
        try:
            slow_tasks = {
                self.model.fetch_data: self._on_data_refreshed
            }
            
            self.worker = SlowProcessWorker(slow_tasks)
            self.worker.start()
            
        except Exception as e:
            logger.exception(f"启动数据刷新时出错: {e}")
            
    def _on_data_refreshed(self, data):
        if self._is_shutting_down:
            return
            
        if data:
            index_df, futures_df = data
            if index_df is not None:
                self.index_data_loaded.emit(index_df)
            if futures_df is not None:
                self.futures_data_loaded.emit(futures_df)
    
    def show_index_chart(self, symbol_code: str):
        self.chart_data_ready.emit("index", symbol_code)
    
    def show_futures_chart(self, symbol: str):
        self.chart_data_ready.emit("futures", symbol)
    
    def cleanup(self):
        # 设置关闭标志，防止新的任务启动
        self._is_shutting_down = True
        
        try:
            self.stop_auto_refresh()
        except Exception as e:
            logger.warning(f"停止自动刷新时出错: {e}")
        
        try:
            if self.worker and self.worker.isRunning():
                self.worker.shutdown()
        except Exception as e:
            logger.warning(f"关闭worker时出错: {e}")
        
        # 清理引用
        try:
            self.worker = None
        except Exception as e:
            logger.warning(f"清理worker引用时出错: {e}")